# !/usr/bin/env python
# -*- coding: utf-8 -*-
# ///////////////////////////////////////////////////////////////
# @File    :   parserList.py
# @Time    :   2024/08/17 10:17:45
# @Author  :   kai.luo
# @Version :   1.0.0
# @Desc    :   Analyze the obtained image recognition data
# ///////////////////////////////////////////////////////////////

import copy
import re


class ParserList(object):
    def __init__(self) -> None:
        self.form_k_data = list()
        self.form_kv_data = list()
        self.title_list = list()

    def filterKeyList(self, data: list):
        """
        根据x获取数据
        Args:
            data (_type_): _description_
        """
        copy_data = copy.deepcopy(data)
        compare_x = float()
        compare_y = float()
        temp_data = list()
        for index, item in enumerate(data):
            text_region = item.get('text_region', [])
            x, y = text_region[0]
            if index == 0:
                compare_x = x
                compare_y = y
                temp_data.append(item)
                copy_data.remove(item)
            else:
                if abs(compare_x-x) <= 10:
                    temp_data.append(item)
                    copy_data.remove(item)

        self.form_k_data.append(temp_data)
        if temp_data:
            self.filterKeyList(copy_data)

    def filterKeyMapValue(self, data: list):
        """
        根据Y筛选数据
        Args:
            data (_type_): 二维数组
        """
        key_dict = data[0]
        copy_data = copy.deepcopy(data[1:])
        if len(data[0]) > 1:  # 默认两个以上的元素为列数据
            for item in key_dict:
                key_value_list = list()
                text = item.get('text', '')
                text_region = item.get('text_region', [])
                x, y = text_region[0]

                isBreak = False
                for index, list_item in enumerate(copy_data):
                    if index > 2:
                        break
                    for dict_item in list_item:
                        text_m = dict_item.get('text', '')
                        text_region_m = dict_item.get('text_region', [])
                        x_m, y_m = text_region_m[0]
                        if abs(y - y_m) <= 8:
                            key_value_list.extend([text, text_m])
                            list_item.remove(dict_item)
                            isBreak = True
                            break
                    if isBreak:
                        break

                if not key_value_list:  # key值无对应的value
                    key_value_list.extend([text, ''])

                self.form_kv_data.append(key_value_list)

        copy_data = [x for x in copy_data if x]
        if len(copy_data) != 0:
            self.filterKeyMapValue(copy_data)

    def filterTitle(self, data: list):
        """
        过滤项目头部标题

        Args:
            data (list): _description_
        """
        perv_pos = int()
        for index, item in enumerate(data):
            text = item.get('text', '')
            text_region_m = item.get('text_region', [])
            x_m, y_m = text_region_m[-1]
            if index == 0:
                perv_pos = y_m
                continue
            if abs(perv_pos-y_m) <= 3:
                self.title_list.append(text)
                perv_pos = y_m

    def filterItems(self, data: list):
        """
        过滤项目
        Args:
            data (list): 数据
        """
        prev_pos = int()
        items_list = list()
        form_items_list = list()
        for index, item in enumerate(data):
            text = item.get('text', '')
            text_region = item.get('text_region', [])
            x, y = text_region[0]

            if index == 0:
                items_list.append(text)
                prev_pos = y
                continue

            if abs(prev_pos-y) <= 4:
                items_list.append(text)
                prev_pos = y
            else:
                prev_pos = y
                form_items_list.append(items_list)
                items_list = []
                items_list.append(text)

        return form_items_list

    def filterfooter(self, data: list):
        """
        过滤尾部
        获取报告日期，地址，电话，主检，审核
        Args:
            data (list): _description_
        """
        form_footer_list = list()
        for item in data:
            text = item.get('text', '')
            if re.findall(r'报\s*告[\u4e00-\u9fff|\u3000-\u303f]{0,2}\：', text.strip()):
                report_time_list = re.findall(
                    r'报告.{0,2}[:：]\s*(\d+\-\d+\-\d{1,2})\s*(\d+[:：]\d+[:：]\d+)*', text.strip())
                if report_time_list:
                    report_time = report_time_list[0][0]+' '+report_time_list[0][1]
                    form_footer_list.append(['报告日期', report_time])
                else:
                    form_footer_list.append(['报告日期', ''])
            elif '电话：' in text.replace(' ', ''):
                report_tel = re.findall(r'电话[:：]\s*(\d+\-\d+\-*\d*)', text.strip())
                if report_tel:
                    form_footer_list.append(['电话', report_tel[0]])
                else:
                    form_footer_list.append(['电话', ''])
            elif '地址：' in text.replace(' ', ''):
                report_addr = re.findall(r'地址[:：](.*)', text.strip())
                if report_addr:
                    form_footer_list.append(['地址', report_addr[0].replace(' ', '')])
                else:
                    form_footer_list.append(['地址', ''])
            elif re.findall(r'主\s*检[\u4e00-\u9fff|\u3000-\u303f]{0,1}\：', text.strip()) or re.findall(r'检\s*验[\u4e00-\u9fff|\u3000-\u303f]{0,1}\：', text.strip()):
                report_owner = re.findall(
                    r'检[\u4e00-\u9fff|\u3000-\u303f]{0,3}[:|：]([\u4e00-\u9fff]{2,3})\s', text.strip())
                if report_owner:
                    form_footer_list.append(['检验人', report_owner[0]])
                else:
                    form_footer_list.append(['检验人', ''])

                if re.findall(r'审\s*核[\u4e00-\u9fff|\u3000-\u303f]{0,1}\：', text.strip()) or re.findall(r'复\s*核[\u4e00-\u9fff|\u3000-\u303f]{0,1}\：', text.strip()):
                    report_check = re.findall(
                        r'核[\u4e00-\u9fff|\u3000-\u303f]{0,1}[:|：]([\u4e00-\u9fff]{2,3})', text.strip())
                    if report_check:
                        form_footer_list.append(['审核人', report_check[0]])
                    else:
                        form_footer_list.append(['审核人', ''])
            elif re.findall(r'审\s*核[\u4e00-\u9fff|\u3000-\u303f]{0,1}\：', text.strip()) or re.findall(r'复\s*核[\u4e00-\u9fff|\u3000-\u303f]{0,1}\：', text.strip()):
                report_check = re.findall(
                    r'核[\u4e00-\u9fff|\u3000-\u303f]{0,1}[:|：]([\u4e00-\u9fff]{2,3})', text.strip())
                if report_check:
                    form_footer_list.append(['审核人', report_check[0]])
                else:
                    form_footer_list.append(['审核人', ''])

        return form_footer_list
